package com.ecas.core.serial.protostuff;

import com.ecas.core.serial.Serialization;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author dewen.ye
 * @date 2019/2/1 02:20
 */
public class ProtosuffSerialzation implements Serialization {
    private static Logger LOG = LoggerFactory.getLogger(ProtosuffSerialzation.class);

    public <T> byte[] serialize(T t, Class<T> clazz) {
        long start = System.currentTimeMillis();
        Schema<T> schema = RuntimeSchema.getSchema(clazz);
        LinkedBuffer buffer = LinkedBuffer.allocate(4096);
        byte[] protostuff = null;
        try {
            protostuff = ProtostuffIOUtil.toByteArray(t, schema, buffer);
        } finally {
            buffer.clear();
        }
        long end = System.currentTimeMillis();
        LOG.info("serialize  object to byte  length:{} cost time:{}", protostuff.length, (end - start));
        return protostuff;
    }


    public <T> T deserialize(byte[] bytes, T t, Class<T> clazz) {
        long start = System.currentTimeMillis();
        Schema<T> schema = RuntimeSchema.getSchema(clazz);
        ProtostuffIOUtil.mergeFrom(bytes, t, schema);
        long end = System.currentTimeMillis();
        LOG.info("deserialize byte to object  cost time:{}", (end - start));
        return t;
    }
}
